﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
using System.IO;
using NPOI.HSSF.UserModel;
using System.Data;
using System.Net;
using NPOI.HPSF;
using System.Text;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using Ext.Net;
using Activity;

    /// <summary>
/// Npoi帮助类
    /// </summary>
public class NpoiHelper
{
    protected static MyDbHelper mydb = new MyDbHelper();
    protected static ExtBaseRpt br = new ExtBaseRpt();
    /// <summary>
    /// DataTable导出到Excel文件
    /// </summary>
    /// <param name="dtSource">源DataTable</param>
    /// <param name="strHeaderText">表头文本</param>
    /// <param name="strFileName">保存位置</param>
    public static void Export(DataTable dtSource, string strHeaderText, string strFileName)
    {
        using (MemoryStream ms = Export(dtSource, strHeaderText))
        {
            using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
            {
                byte[] data = ms.ToArray();
                fs.Write(data, 0, data.Length);
                fs.Flush();
            }
        }
    }

    /// <summary>
    /// DataTable导出到Excel的MemoryStream
    /// </summary>
    /// <param name="dtSource">源DataTable</param>
    /// <param name="strHeaderText">表头文本</param>
    public static MemoryStream Export(DataTable dtSource, string strHeaderText)
    {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();

        #region 右击文件 属性信息
        {
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "NPOI";
            workbook.DocumentSummaryInformation = dsi;

            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Author = "文件作者信息"; //填加xls文件作者信息
            si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息
            si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息
            si.Comments = "作者信息"; //填加xls文件作者信息
            si.Title = "标题信息"; //填加xls文件标题信息
            si.Subject = "主题信息";//填加文件主题信息
            si.CreateDateTime = DateTime.Now;
            workbook.SummaryInformation = si;
        }
        #endregion

        HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle();
        HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat();
        dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");

        //取得列宽
        int[] arrColWidth = new int[dtSource.Columns.Count];
        foreach (DataColumn item in dtSource.Columns)
        {
            arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
        }
        for (int i = 0; i < dtSource.Rows.Count; i++)
        {
            for (int j = 0; j < dtSource.Columns.Count; j++)
            {
                int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
                if (intTemp > arrColWidth[j])
                {
                    arrColWidth[j] = intTemp;
                }
            }
        }
        int rowIndex = 0;
        foreach (DataRow row in dtSource.Rows)
        {
            #region 新建表，填充表头，填充列头，样式
            if (rowIndex == 65535 || rowIndex == 0)
            {
                if (rowIndex != 0)
                {
                    sheet = (HSSFSheet)workbook.CreateSheet();
                }

                #region 表头及样式
                {
                    HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0);
                    headerRow.HeightInPoints = 25;
                    headerRow.CreateCell(0).SetCellValue(strHeaderText);

                    HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
                    headStyle.Alignment = HorizontalAlignment.Center;
                    HSSFFont font = (HSSFFont)workbook.CreateFont();
                    font.FontHeightInPoints = 20;
                    font.Boldweight = 700;
                    headStyle.SetFont(font);
                    headerRow.GetCell(0).CellStyle = headStyle;
                    sheet.AddMergedRegion(new NPOI.SS.Util.Region(0, 0, 0, dtSource.Columns.Count - 1));
                    //headerRow.Dispose();
                }
                #endregion


                #region 列头及样式
                {
                    HSSFRow headerRow = (HSSFRow)sheet.CreateRow(1);
                    HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
                    headStyle.Alignment = HorizontalAlignment.Center;
                    HSSFFont font = (HSSFFont)workbook.CreateFont();
                    font.FontHeightInPoints = 10;
                    font.Boldweight = 700;
                    headStyle.SetFont(font);
                    foreach (DataColumn column in dtSource.Columns)
                    {
                        headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                        headerRow.GetCell(column.Ordinal).CellStyle = headStyle;

                        //设置列宽
                        sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
                    }
                    //headerRow.Dispose();
                }
                #endregion

                rowIndex = 2;
            }
            #endregion


            #region 填充内容
            HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);
            foreach (DataColumn column in dtSource.Columns)
            {
                HSSFCell newCell = (HSSFCell)dataRow.CreateCell(column.Ordinal);

                string drValue = row[column].ToString();

                switch (column.DataType.ToString())
                {
                    case "System.String"://字符串类型
                        newCell.SetCellValue(drValue);
                        break;
                    case "System.DateTime"://日期类型
                        DateTime dateV;
                        DateTime.TryParse(drValue, out dateV);
                        newCell.SetCellValue(dateV);

                        newCell.CellStyle = dateStyle;//格式化显示
                        break;
                    case "System.Boolean"://布尔型
                        bool boolV = false;
                        bool.TryParse(drValue, out boolV);
                        newCell.SetCellValue(boolV);
                        break;
                    case "System.Int16"://整型
                    case "System.Int32":
                    case "System.Int64":
                    case "System.Byte":
                        int intV = 0;
                        int.TryParse(drValue, out intV);
                        newCell.SetCellValue(intV);
                        break;
                    case "System.Decimal"://浮点型
                    case "System.Double":
                        double doubV = 0;
                        double.TryParse(drValue, out doubV);
                        newCell.SetCellValue(doubV);
                        break;
                    case "System.DBNull"://空值处理
                        newCell.SetCellValue("");
                        break;
                    default:
                        newCell.SetCellValue("");
                        break;
                }

            }
            #endregion

            rowIndex++;
        }
        using (MemoryStream ms = new MemoryStream())
        {
            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;
            //sheet.Dispose();
            //workbook.Dispose();//一般只用写这一个就OK了，他会遍历并释放所有资源，但当前版本有问题所以只释放sheet
            return ms;
        }
    }
 
         /// <summary>
         /// 用于Web导出
         /// </summary>
         /// <param name="dtSource">源DataTable</param>
         /// <param name="strHeaderText">表头文本</param>
         /// <param name="strFileName">文件名</param>
    public static string ExportByWeb(string mid, DataSet dtSource,string strFileName)
    {
        // 设置编码和附件格式
        /*
                MemoryStream ms = ExportDataSetToExcelPageCount(mid, dtSource, strFileName) as MemoryStream;
                var data = ms.GetBuffer();
                ms.Dispose();
                ms = null;
                try
                {
                    response.Buffer = true;
                    response.Clear();
                    response.ContentType = "application/msexcel";
                    response.AppendHeader("Content-Disposition",
                        "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));
                    response.BinaryWrite(data);
                    response.Flush();
                    response.End();
                }
                catch(Exception ex) { }
         */

        var strPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//获取或设置包含该应用程序的目录的名称。
        if (!Directory.Exists(strPath + "UploadFile"))
        {
            Directory.CreateDirectory(strPath + "UploadFile\\Excel"); //不存在就创建文件夹 } 
        }
        if (!Directory.Exists(strPath + "UploadFile\\Excel"))
        {
            Directory.CreateDirectory(strPath + "UploadFile\\Excel"); //不存在就创建文件夹 } 
        }
        var dyInfo = new DirectoryInfo(strPath + "UploadFile\\Excel");
        try
        {
            //获取文件夹下所有的文件
            foreach (FileInfo feInfo in dyInfo.GetFiles())
            {
                //判断文件日期是否小于2小时，是则删除
                if (feInfo.CreationTime < DateTime.Now.AddHours(-1))
                    feInfo.Delete();
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        var fieldName= strFileName + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
        var filePath = strPath + "UploadFile\\Excel\\" + fieldName;
        MemoryStream ms = ExportDataSetToExcelPageCount(mid, dtSource) as MemoryStream;
        FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
        byte[] data = ms.ToArray();
        fs.Write(data, 0, data.Length);
        fs.Flush();
        fs.Close();
        ms.Close();
        data = null;
        ms = null;
        fs = null;

        return filePath.Replace("\\", "#");;
        //X.Msg.Prompt("提示", "生成成功！", new JFunction { Handler = "alert(1);outExcle('" + path + "');" }).Show();
        //X.Msg.Alert("提示", "点击下载>>：<a href='http://rpt.erp-km.cn:8088/UploadFile/" + strHeaderText + ".xls'>" + strFileName + "</a>").Show();

        //response.AppendHeader("Content-Disposition", "attachment;filename=" + strFileName);
        //response.BinaryWrite(ms.ToArray());
        //response.End();
    }

    private static Stream ExportDataSetToExcel(string mid ,DataSet sourceDs, string sheetName)
    {
        HSSFWorkbook workbook = new HSSFWorkbook();
        MemoryStream ms = new MemoryStream();
        string displayname = "";
        string[] sheetNames = sheetName.Split(',');
        for (int i = 0; i < sheetNames.Length; i++)
        {
            ISheet sheet = workbook.CreateSheet(sheetNames[i]);
            IRow headerRow = sheet.CreateRow(0);
            // handling header.
            foreach (DataColumn column in sourceDs.Tables[i].Columns)
            {
                try
                {
                    displayname = mydb.DM_GetExecuteScalarObj(@"select isnull(FieldDisplay,'') from [dbo].[Sys_ModulesLayout]a 
                    inner join sys_modules m on m.mid = a.mid 
                    where m.parentid =" + mid + " and FieldName = '" + column.ColumnName + "'").ToString();
                }
                catch { }
                headerRow.CreateCell(column.Ordinal).SetCellValue(displayname == "" ? column.ColumnName : displayname);
            }
            // handling value.
            int rowIndex = 1;
            foreach (DataRow row in sourceDs.Tables[i].Rows)
            {
                IRow dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in sourceDs.Tables[i].Columns)
                {
                    dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                }
                rowIndex++;
            }
        }
        workbook.Write(ms);
        ms.Flush();
        ms.Position = 0;
        workbook = null;
        return ms;
    }
    /// <summary>
    /// 分页导出EXCEL
    /// </summary>
    /// <param name="mid"></param>
    /// <param name="sourceDs"></param>
    /// <param name="sheetName"></param>
    /// <returns></returns>
    public static Stream ExportDataSetToExcelPageCount(string mid, DataSet sourceDs)
    {

        try
        {
            var columnList = mydb.DM_GetDateSet(@"select FieldName,FieldDisplay from [dbo].[Sys_ModulesLayout]a 
                    inner join sys_modules m on m.mid = a.mid 
                    where m.parentid =" + mid);
            var columTab = columnList.Tables[0];


            HSSFWorkbook workbook = new HSSFWorkbook();
            MemoryStream ms = new MemoryStream();
            string displayname = "";
            var dt = sourceDs.Tables[0];
            DataRow[] fieldRow = null;
            //string[] sheetNames = sheetName.Split(',');
            var sheetRow = 65535;
            int sheetNum = (int)Math.Ceiling(dt.Rows.Count * 1.0 / sheetRow);
            for (int sheetIndex = 0; sheetIndex < sheetNum; sheetIndex++)
            {
                ISheet sheet = workbook.CreateSheet("数据_" + sheetIndex.ToString());
                IRow headerRow = sheet.CreateRow(0);
                // handling header.
                foreach (DataColumn column in dt.Columns)
                {
                    fieldRow = columTab.Select("FieldName = '" + column.ColumnName + "'");
                    if(fieldRow.Any())
                        displayname = fieldRow[0]["FieldDisplay"].ToString();
                    headerRow.CreateCell(column.Ordinal).SetCellValue(displayname == "" ? column.ColumnName : displayname);
                }
                var iRow = 1;
                var startRow = sheetIndex * (sheetRow - 1);
                var endRow = (sheetIndex + 1) * (sheetRow - 1);
                endRow = endRow <= dt.Rows.Count ? endRow : dt.Rows.Count;

                ICell cell = null;
                for (var rowIndex = startRow; rowIndex < endRow; rowIndex++)
                {
                    IRow row = sheet.CreateRow(iRow);
                    row.Height = 80 * 20;
                    var colIndex = 0;
                    foreach (DataColumn item in dt.Columns)
                    {
                        var cellValue = dt.Rows[rowIndex][item.ToString()];
                        var cellValueStr = cellValue != DBNull.Value ? cellValue.ToString() : string.Empty;
                        if ((cellValueStr.ToUpper().EndsWith(".JPG") || cellValueStr.ToUpper().EndsWith(".JPEG") ||
                             cellValueStr.ToUpper().EndsWith(".PNG")) && cellValueStr.ToUpper().StartsWith("HTTP"))
                        {
                            InsertPicture(cellValueStr, workbook, sheet, rowIndex + 1, colIndex);
                        }
                        else
                        {
                            cell = row.CreateCell(item.Ordinal);
                            cell.SetCellValue(cellValue != DBNull.Value ? ReplaceHtmlTag(cellValue.ToString()) : string.Empty);
                        }
                        colIndex++;
                    }
                    iRow++;
                }
            }
            workbook.Write(ms);
            //ms.Flush();
            //ms.Position = 0;
            workbook = null;
            return ms;
        }
        catch(Exception ex)
        {
            Log.Error("导出报错：" + ex.Message);
            throw ex;
        }
    }

    public static void InsertPicture(string Url, HSSFWorkbook workbook, ISheet sheet,int rowIndex,int colIndex)
    {
        var MyWebClient = new WebClient();

        var strPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; //获取或设置包含该应用程序的目录的名称。

        if (!Directory.Exists(strPath + "oosPicture"))
        {
            Directory.CreateDirectory(strPath + "oosPicture"); //不存在就创建文件夹 }
        }

        var fileName = Url.Substring(Url.LastIndexOf("/") + 1);

        var path = string.Format("{0}\\oosPicture\\{1}", strPath, fileName);
        if (!File.Exists(path))
        {
            Byte[] pageData = MyWebClient.DownloadData(Url);
            File.WriteAllBytes(path, pageData);
        }
        byte[] bytes = System.IO.File.ReadAllBytes(path);
        var pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG);
        var patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
        // 插图片的位置  HSSFClientAnchor（dx1,dy1,dx2,dy2,col1,row1,col2,row2) 后面再作解释
        var anchor = new HSSFClientAnchor(70, 10, 0, 0, colIndex, rowIndex, colIndex + 1, rowIndex + 1);
        //把图片插到相应的位置
        var pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);
    }

    public static string ReplaceHtmlTag(string html, int length = 0)
    {
        string strText = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", "");
        strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", "");

        if (length > 0 && strText.Length > length)
            return strText.Substring(0, length);

        return strText;
    }
}
